<template>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" :close-on-click-modal="false" @close="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="96px">
            <el-row>
                <el-col :span="24" style="margin-bottom: 20px"><b>{{ $locale('geWudevice.add.Basic information') }}</b></el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item :label="$locale('geWudevice.add.name')" prop="experimentName">
                        <el-input :disabled="disabled" v-model="form.experimentName" :placeholder="$locale('geWudevice.add.Please enter a name')" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$locale('myExperiment.add.Experimental classification')" prop="experimentType">
                        <el-select :disabled="disabled" v-model="form.experimentType" :placeholder="$locale('geWuExperiment.classification')" clearable collapse-tags>
                            <el-option v-for="dict in dict.type.experiment_type" :key="dict.value" :label="dict.label" :value="+dict.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$locale('geWuExperiment.grade')" prop="level">
                        <el-select v-model="form.level" :placeholder="$locale('geWuExperiment.grade')" clearable style="width: 240px">
                            <el-option v-for="dict in levelList" :key="dict.id" :label="dict.levelName" :value="dict.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$locale('geWuExperiment.author')" prop="createBy">
                        <el-input :disabled="disabled" v-model="form.createBy" :placeholder="$locale('myExperiment.add.Please enter the author')" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$locale('geWuExperiment.difficulty')" prop="difficultyLevel">
                        <el-rate :disabled="disabled" v-model="form.difficultyLevel" show-text :texts="['1星', '2星', '3星', '4星', '5星']"></el-rate>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$locale('geWuExperiment.Experimental time')" prop="experimentTime">
                        <el-rate
                            :disabled="disabled"
                            v-model="form.experimentTime"
                            :icon-classes="['el-icon-timer', 'el-icon-timer', 'el-icon-timer']"
                            show-text
                            :texts="['15分钟', '30分钟', '45分钟', '60分钟', '75分钟']"
                            void-icon-class="el-icon-timer"></el-rate>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$locale('geWuExperiment.Is it publicly available')" prop="isOpen">
                        <el-select :disabled="disabled" v-model="form.isOpen" :placeholder="$locale('geWuExperiment.Is it publicly available')" clearable>
                            <el-option :label="$locale('geWuExperiment.yes')" :value="true" />
                            <el-option :label="$locale('geWuExperiment.no')" :value="false" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item :label="$locale('geWudevice.Creation time')" prop="createTime">
                        <el-date-picker
                            :disabled="disabled"
                            v-model="form.createTime"
                            format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            type="datetime"
                            :placeholder="$locale('myClass.add.Select date and time')"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item :label="$locale('myExperiment.add.Experimental images')" prop="experimentPicture">
                        <ImageUpload :disabled="disabled" @input="changeImage" :value="form.experimentPicture" :fileType="['png', 'jpg', 'jpeg']" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" style="margin-bottom: 20px"><b>{{ $locale('myExperiment.add.Experimental information') }}</b></el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-tabs v-model="activeName" @tab-click="handleClick">
                        <el-tab-pane :label="$locale('geWudevice.add.describe')" name="first">
                            <editor :readOnly="disabled" v-model="form.description" :height="180" />
                        </el-tab-pane>
                        <el-tab-pane :label="$locale('myDevice.determinedList.device')" name="second">
                            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddDevice" v-if="!disabled">
                              {{ $locale('myExperiment.add.Add Device') }}</el-button>
                            <el-table :data="form.experimentDevices" v-loading="loading" :max-height="180">
                                <el-table-column type="index" width="50" :label="$locale('geWudevice.add.Serial Number')"></el-table-column>
                                <el-table-column :label="$locale('geWudevice.Equipment number')" align="center" prop="deviceNum" width="160"></el-table-column>
                                <el-table-column :label="$locale('geWudevice.Equipment name')" align="center" key="deviceName" prop="deviceName" :show-overflow-tooltip="true"></el-table-column>
                                <el-table-column :label="$locale('geWudevice.quantity')" align="center" key="deviceTotal" prop="deviceTotal"></el-table-column>
                                <el-table-column :label="$locale('myExperiment.add.Location of turnover box')" align="center" key="parentBoxName" prop="parentBoxName" width="120"></el-table-column>
                                <el-table-column :label="$locale('myExperiment.add.picture')" align="center" key="devicePicture" prop="devicePicture">
                                    <template slot-scope="scope">
                                        <ImagePreview v-if="scope.row.devicePicture" :src="scope.row.devicePicture" :height="30" />
                                    </template>
                                </el-table-column>
                                <el-table-column :label="$locale('操作')" align="center" width="160" class-name="small-padding fixed-width">
                                    <template slot-scope="scope">
                                        <el-button :disabled="disabled" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.$index)">
                                          {{ $locale('formMarkering.list.delete') }}</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <!-- <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="handleClick" /> -->
                        </el-tab-pane>
                        <el-tab-pane :label="$locale('myExperiment.add.Experimental Guide Book')" name="third">
<!--                            <el-col :span="24">-->
<!--                                <el-form-item label="教师版：" prop="teacherGuidebook">-->
<!--                                    <FileUpload :disabled="disabled" @input="changeFileStudent" :value="form.teacherGuidebook" :fileType="['gewu']" />-->
<!--                                </el-form-item>-->
<!--                            </el-col>-->
                            <el-col :span="24">
                                <el-form-item :label="$locale('myExperiment.add.Upload guidebook')" prop="guidebook">
                                    <FileUpload ref="refFileUpload" :disabled="disabled" @input="changeFileTeacher" :value="form.guidebook" :fileType="['gewu']" is-show-tip />
                                </el-form-item>
                            </el-col>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer" v-if="!disabled">
            <el-button type="primary" @click="submitForm(0)">{{ $locale('myDevice.determinedList.add.Save draft') }}</el-button>
            <el-button type="primary" @click="submitForm(1)">{{ $locale('school.add.Submit') }}</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
        <el-dialog :title="$locale('myExperiment.add.Add Device')" :visible.sync="openAdd" width="400px" append-to-body>
            <el-form ref="formData" :model="formData" :rules="formDataRules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item :label="$locale('myDevice.determinedList.add.Equipment source')" prop="deviceSource">
                            <el-radio-group v-model="formData.deviceSource" @change="getgetSchoolTurnoverBoxListFc">
                                <el-radio label="1">{{ $locale('myExperiment.add.There are already turnover boxes available') }}</el-radio>
                                <el-radio label="2">{{ $locale('myExperiment.add.List of Equipment for Sorting') }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="formData.deviceSource == '1'">
                        <el-form-item :label="$locale('myDevice.determinedList.turnover box')" prop="boxId">
                            <el-select v-model="formData.boxId" filterable :placeholder="$locale('myExperiment.add.Please select a turnover box')" style="width: 100%" @change="getDeviceId">
                                <el-option v-for="item in turnoverBoxList" :key="item.deviceId" :label="item.deviceName" :value="item.deviceId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item v-if="formData.deviceSource == '1'" :label="$locale('myDevice.determinedList.device')" prop="deviceId">
                            <el-select v-model="formData.deviceId" filterable :placeholder="$locale('myExperiment.add.Please select a device')" style="width: 100%">
                                <el-option v-for="item in getDeviceListByBoxIdList" :key="item.id" :label="item.deviceName" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-else :label="$locale('myDevice.determinedList.device')" prop="deviceId">
                            <el-autocomplete
                                @select="handleSelect"
                                :debounce="0"
                                v-model="formData.deviceId"
                                :fetch-suggestions="querySearchAsync"
                                :placeholder="$locale('myExperiment.add.Search based on device name or device number')"
                                style="width: 100%"></el-autocomplete>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$locale('geWudevice.quantity')" prop="deviceTotal">
                            <el-input-number v-model="formData.deviceTotal" :placeholder="$locale('student.Enter')" controls-position="right" :min="0" style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addForm">{{ $locale('school.add.Submit') }}</el-button>
            </div>
        </el-dialog>
    </el-dialog>
</template>

<script>
import { formatDate } from '@/utils/index';
import { getExperimentDeviceListByExperimentId, addExperiment, editExperiment } from '@/api/geWuExperiment';
import { getListByDeviceNameOrDeviceNum } from '@/api/geWudevice';
import { getLevelList } from '@/api/myClass/levelList';
import { getSchoolTurnoverBoxList, getDeviceListByBoxId } from '@/api/myDevice';

export default {
    name: 'experimentAdd',
    dicts: ['experiment_type'],
    data() {
        return {
            // 遮罩层
            loading: false,
            loadingRemote: false,
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            openAdd: false,
            // 表单参数
            form: {
                experimentDevices: []
            },
            // 总条数
            total: 0,
            levelList: [],
            disabled: false,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                schoolId: undefined
            },
            formData: {
                deviceSource: [],
                deviceId: '',
                deviceName: '',
                deviceTotal: undefined
            },
            activeName: 'first',
            turnoverBoxList: [],
            experimentTimeObj: {
                15: 1,
                30: 2,
                45: 3,
                60: 4,
                75: 5
            },
            getDeviceListByBoxIdList: [],
            // 表单校验
            rules: {},
            selectedItem: [],
            // 表单校验
            formDataRules: {
                deviceTotal: [{ required: true, message: this.$locale('geWudevice.add.tip1'), trigger: 'blur' }]
            }
        };
    },
    created() {},
    methods: {
        changeFileTeacher(fileList) {
          console.log(fileList);
          this.form.guidebook = fileList;
        },
        changeFileStudent(fileList) {
            this.form.teacherGuidebook = fileList;
        },
        handleAddDevice() {
            this.resetForm('formData');
            this.openAdd = true;
            this.formData.deviceSource = '1';
            this.getDeviceListByBoxIdList = [];
            this.turnoverBoxList = [];
            this.getgetSchoolTurnoverBoxListFc();
        },
        getgetSchoolTurnoverBoxListFc() {
            if (this.formData.deviceSource == '1') {
                getSchoolTurnoverBoxList().then(({ data }) => {
                    this.turnoverBoxList = data;
                });
            }
        },
        getDeviceId() {
            if (this.formData.deviceSource == '1') {
                getDeviceListByBoxId(this.formData.boxId).then(({ data }) => {
                    this.getDeviceListByBoxIdList = data;
                });
            }
        },
        querySearchAsync(queryString, cb) {
            if (!queryString) {
                cb([]);
                return;
            }
            getListByDeviceNameOrDeviceNum({ deviceNameOrDeviceNum: queryString })
                .then(({ data }) => {
                    let dataList = data.map((item) => {
                        item['value'] = item.deviceName;
                        return item;
                    });
                    cb(dataList); // 确保 data 格式符合期望
                })
                .catch((error) => {
                    console.error(this.$locale('student.add.Query failed'), error);
                    cb([]); // 出错时返回空结果
                });
        },
        handleSelect(item) {
            this.selectedItem = item;
            this.selectedItem['deviceId'] = item.id;
        },
        handleClick() {},
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.handleClick();
        },
        // 上传成功
        changeImage(fileList) {
            this.form.experimentPicture = fileList;
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },
        // 表单重置
        reset() {
            this.form = {};
            this.resetForm('form');
        },
        /** 新增按钮操作 */
        handleAdd(form) {
            this.reset();
            this.form.experimentDevices = this.form.experimentDevices ? this.form.experimentDevices : [];
            this.open = true;
            this.title = this.$locale('myExperiment.add.Add experiment');
            this.form.createBy = this.$store.getters.name;
            this.$set(this.form, 'createTime', formatDate(new Date()));
            getLevelList().then(({ data }) => {
                this.levelList = data;
            });
        },
        /** 修改按钮操作 */
        handleUpdate(row, disabled) {
            this.disabled = disabled || false;
            getExperimentDeviceListByExperimentId(row.id).then(({ data }) => {
                this.reset();
                this.form = this.deepClone(row);
                this.form.experimentDevices = data;
                this.form.experimentTime = this.experimentTimeObj[this.form.experimentTime];
                this.open = true;
                this.title = disabled ? this.$locale('myExperiment.add.View experiment') : this.$locale('myExperiment.add.Modify experiment');
                this.$forceUpdate()
            });
            getLevelList().then(({ data }) => {
                this.levelList = data;
            });
        },
        /** 删除按钮操作 */
        handleDelete(index) {
            this.form.experimentDevices.splice(index, 1);
        },
        /** 提交按钮 */
        submitForm: function (status) {
            let form = this.deepClone(this.form);
            form.experimentTime = this.getKeyByValue(this.experimentTimeObj, form.experimentTime);
            form.status = status;
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (form.id != undefined) {
                        editExperiment(form).then((response) => {
                            this.$modal.msgSuccess(this.$locale('geWudevice.add.tip5'));
                            this.open = false;
                            this.$emit('getList');
                        });
                    } else {
                        addExperiment(form).then((response) => {
                            this.$modal.msgSuccess(this.$locale('geWudevice.add.tip6'));
                            this.open = false;
                            this.$emit('getList');
                        });
                    }
                    this.$refs.refFileUpload.$clear()
                }
            });
        },
        /** 新增按钮 */
        addForm: function () {
            this.$refs['formData'].validate((valid) => {
                if (this.formData.deviceSource == '1') {
                    const box = this.getDeviceListByBoxIdList.find((item) => item.id === this.formData.deviceId);
                    let newDevices = Array(1).fill(box);
                    newDevices = newDevices.map(({ id, ...rest }) => ({
                        ...rest,
                        deviceTotal: this.formData.deviceTotal
                    }));
                    this.form.experimentDevices.push(...newDevices);
                } else {
                    let newDevices = Array(1).fill(this.selectedItem);
                    newDevices = newDevices.map(({ id, ...rest }) => ({
                        ...rest,
                        deviceTotal: this.formData.deviceTotal
                    }));
                    this.form.experimentDevices.push(...newDevices);
                }
                this.openAdd = false;
                // add(this.formData).then(response => {
                //     this.$modal.msgSuccess("新增成功");
                //     this.openAdd = false;
                //     this.handleClick();
                // });
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.activeName = 'first';
            this.reset();
        }
    }
};
</script>

<style lang="scss" scoped>
.el-rate {
    line-height: 2;
}
</style>
